package uk.org.landeg.euler.problems;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.org.landeg.euler.problems.framework.AbstractProblem;
import uk.org.landeg.euler.problems.framework.ProblemLauncher;
import uk.org.landeg.euler.problems.lib.NumbersLib;
import uk.org.landeg.euler.problems.lib.StringsLib;

public class Problem042 extends AbstractProblem{
	Set<Integer> triangles = new TreeSet<Integer>();
	Vector<String> words = new Vector<String>();
	
	public static void main(String[] args) {
		ProblemLauncher launcher = new ProblemLauncher(new Problem042());
		launcher.solve();		
	}

	@Override
	public Object solve() {
		Pattern p = Pattern.compile("\\w+");
		try {
			BufferedReader reader = new BufferedReader(new FileReader("data/words.txt"));
			String line = reader.readLine();
			Matcher m = p.matcher(line);
			int maxLen = 0;
			String thisWord;
			notes.add("Parsing words list");
			while (m.find()) {
				thisWord = m.group();
				words.add(thisWord);
				maxLen = (thisWord.length() > maxLen) ? thisWord.length() : maxLen;
			}
			notes.add("max word length is " + maxLen);
			thisWord = "";
			for (int n = 0 ; n<=maxLen ; n++) {
				thisWord = thisWord.concat("z");
			}
			int maxScore = StringsLib.wordScore(thisWord);
			notes.add("Highest possible word is " + thisWord + "(" + maxScore + ")");
			int score = 0;
			notes.add("Max possible score is " + maxScore);
			int t = 0;
			while (t < maxScore) {
				t = (int)NumbersLib.triangle(score++);
				triangles.add(t);
			}
			notes.add("Using triangle set: " + triangles);
			notes.add("Counting triangle words...");
			int count = 0;
			for (String s : words) {
				if (triangles.contains(new Integer(StringsLib.wordScore(s)))) {
					count++;
				}
			}
			return count;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return "how many are triangle words?";
	}

	@Override
	public Integer getProblemNumber() {
		// TODO Auto-generated method stub
		return 42;
	}
}
